package com.xiaodu.yaml.config;

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.DefaultPropertySourceFactory;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Optional;
import java.util.Properties;

/**
 * @author: dutianjie
 * @date: 2021/3/23
 * @version: v1.0.0
 * @description: 描述
 * @email: dutianjie@thunisoft.com
 **/
public class YamlPropertySourceFactory extends DefaultPropertySourceFactory {

    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        String filename = resource.getResource().getFilename();
        String sourceName = Optional.ofNullable(name).orElse(resource.getResource().getFilename());
        if (!resource.getResource().exists()) {
            return new PropertiesPropertySource(sourceName, new Properties());
        }
        if (filename.endsWith(".yaml") || filename.endsWith(".yml")) {
            YamlPropertiesFactoryBean yamlPropertiesFactoryBean = yamlPropertiesFactoryBean(resource);
            return new PropertiesPropertySource(sourceName, yamlPropertiesFactoryBean.getObject());
        }
        return super.createPropertySource(name, resource);
    }

    public YamlPropertiesFactoryBean yamlPropertiesFactoryBean(EncodedResource encodedResource) {
        YamlPropertiesFactoryBean yamlPropertiesFactoryBean = new YamlPropertiesFactoryBean();
        yamlPropertiesFactoryBean.setResources(encodedResource.getResource());
        yamlPropertiesFactoryBean.afterPropertiesSet();
        return yamlPropertiesFactoryBean;
    }
}
